<script setup lang="ts" name="searchBar">
import { useDrag } from '@/utils'
interface Props {
  title?: string
  clipboardItem: IClipboardItem | undefined
  curPlugin?: plugin.PluginElem
}

const props = withDefaults(defineProps<Props>(), {
  title: 'title',
  clipboardItem: undefined
})

const textCardhtml = computed(() => {
  //将换行符替换成符号，展示空格
  //如果字符串长度大于32，则展示前16个字符和后16个字符，中间用......拼接
  let content = props.clipboardItem?.type === 'text' ? props.clipboardItem.content : ''

  //html转义
  if (content.length > 32) {
    content = `${content
      .substr(0, 16)
      .replace(/&/g, '&amp;')
      .replace(/ /g, '&nbsp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')}<span class="hint">......</span>${content
      .substr(content.length - 16, content.length)
      .replace(/&/g, '&amp;')
      .replace(/ /g, '&nbsp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')}`
  }

  content = content
    .replace(/\n/g, '<span class="hint">↵</span>')
    .replace(/\t/g, '<span class="hint">⇥</span>')
  return content
})

const placeHolder = computed(() => {
  if (!props.clipboardItem) {
    return 'Hi,stools'
  }

  if (props.clipboardItem.type === 'file') {
    return '文件'
  } else if (props.clipboardItem.type === 'img') {
    return '图片'
  } else if (props.clipboardItem.type === 'text') {
    return '文本'
  }

  return 'Hi,stools'
})

const inputRef = ref<HTMLInputElement | null>(null)

const mainInput = defineModel<string>('searchVal', { default: '' })

//计算输入框文字的宽度
const inputWidth = computed(() => {
  const span = document.createElement('span')
  span.style.position = 'absolute'
  span.style.visibility = 'hidden'
  span.style.whiteSpace = 'nowrap'
  span.style.whiteSpace = 'pre'
  if (inputRef.value) {
    span.style.fontSize = window.getComputedStyle(inputRef.value as Element).fontSize
  }

  span.innerText = mainInput.value
  document.body.appendChild(span)
  const width = span.clientWidth
  document.body.removeChild(span)

  //查询父元素的宽度
  const parentWidth = inputRef.value?.parentElement?.clientWidth || 0
  //获取attachement的宽度
  const attachment = document.getElementById('attachment')
  const attachmentWidth = attachment?.clientWidth ? attachment.clientWidth + 12 : 0

  // console.log(Math.min(Math.max(width + 1, 1), parentWidth - attachmentWidth - 24))

  return Math.min(Math.max(width + 1, 1), parentWidth - attachmentWidth - 24)
})

const showOpt = () => {
  const tpl = [
    {
      label: '打开开发者工具',
      click: () => {
        window.api.openDevTools()
      }
    }
  ]

  window.electron.menu.buildFromTemplate(tpl).popup()
}

const closePlugin = () => {
  if (mainInput.value !== '') {
    mainInput.value = ''
  }
  emits('goBack')
}

// emits
const emits = defineEmits<{
  goBack: []
}>()

const focus = (select?: boolean) => {
  inputRef.value?.focus()
  if (select) {
    inputRef.value?.select()
  }
}

const { onMouseDown } = useDrag()

const startDrag = (event) => {
  onMouseDown(event)
}

defineExpose({
  focus,
  cursorMoveBlock: (direction: MoveAction) => {
    const { value, selectionStart, selectionEnd } = inputRef.value || {}

    if (!value) {
      return true
    }

    if (selectionStart !== selectionEnd) {
      return false
    }

    return (
      (selectionStart === 0 && (direction === 'left' || direction === 'up')) ||
      (selectionStart === value.length && (direction === 'right' || direction === 'down'))
    )
  }
})

//model
</script>

<template>
  <div class="h-56px flex mx-8px box-border items-center">
    <div
      v-if="curPlugin"
      id="attachment"
      class="flex items-center bg-[#efefef] py-4px pl-12px pr-4px mr-12px rounded-12px max-w-440px"
    >
      <n-image :src="curPlugin.icon" preview-disabled object-fit="contain" width="24" height="24" />

      <span class="text-16px text-[#323232] ml-8px whitespace-nowrap overflow-hidden">{{
        curPlugin.label
      }}</span>

      <!-- close btn -->
      <n-button :focusable="false" text style="font-size: 16px" class="ml-4px" @click="closePlugin">
        <icon-ic:baseline-close
          class="text-[#323232] hover:bg-[#dddddd] rounded-full"
        ></icon-ic:baseline-close>
      </n-button>
    </div>
    <div
      v-else-if="
        clipboardItem?.type === 'file' ||
        clipboardItem?.type === 'img' ||
        clipboardItem?.type === 'text'
      "
      id="attachment"
      class="mr-12px max-w-640px"
    >
      <div
        v-if="props.clipboardItem?.type === 'text'"
        class="box-border text-[#323232] text-16px px-8px h-32px gap-6px py-2px b-1 b-dashed b-[#4444] flex items-center"
        v-html="textCardhtml"
      ></div>
      <div v-else-if="clipboardItem?.type === 'img'" class="f-c-c b-1 b-solid b-[#4444]">
        <n-image
          :src="clipboardItem.content"
          :preview-disabled="true"
          object-fit="contain"
          width="40"
          height="40"
        />
      </div>
      <div
        v-else-if="clipboardItem?.type === 'file' && (clipboardItem?.files.length ?? 0) > 0"
        class="box-border px-8px h-36px gap-6px py-2px b-1 b-solid b-[#4444] flex items-center"
      >
        <n-image
          :src="clipboardItem?.files[0].icon"
          :preview-disabled="true"
          object-fit="contain"
          width="22"
          height="22"
        />
        <span class="text-16px text-[rgb(82, 82, 82)] whitespace-nowrap overflow-hidden">
          {{ clipboardItem?.files[0].name }}
        </span>
        <!-- 标签 -->
        <div
          v-if="(clipboardItem?.files.length ?? 0) > 1"
          class="bg-[rgb(64,64,64)] text-[rgb(250,250,250)] rd-100% min-w-20px h-20px text-14px f-c-c"
        >
          {{ clipboardItem?.files.length }}
        </div>
      </div>
    </div>

    <!-- main input -->

    <input
      ref="inputRef"
      v-model="mainInput"
      autofocus
      :style="{ width: inputWidth + 'px' }"
      class="m-input px-0 box-border h-56px border-none bg-transparent outline-none caret-red text-24px"
    />

    <!-- 拖拽区 -->
    <div
      class="flex-1 h-full flex items-center translate translate-x-[-1px] placeholder"
      @mousedown="startDrag"
    >
      {{ mainInput ? '' : placeHolder }}
    </div>

    <!-- 菜单选项 -->

    <n-button :focusable="false" color="black" text style="font-size: 24px" @click="showOpt">
      <icon-ic:baseline-more-vert></icon-ic:baseline-more-vert>
    </n-button>
  </div>
</template>

<style scoped lang="scss">
.m-input {
  &::selection {
    background-color: red;
    color: white;
  }
}

.placeholder {
  color: #9d9d9d;

  //设置font weight
  font-size: 24px;
  font-weight: 200;
  //文字间距
  letter-spacing: 1px;
}
</style>
